import asyncio
from Alibb.redis import RedisPool
from Alibb.settings import settings
from Alibb.urls import urlspatten

from tornado.web import Application
from wtforms_json import init
from uvloop import EventLoopPolicy


def make_app(loop_):
    apps = Application(urlspatten, **settings, debug=True)

    func = RedisPool(loop=loop_)

    # redis异步库
    apps.redis = func.get_conn()

    # 异步请求库
    apps.session = func.get_aiohttp()

    # aiomysql
    apps.mysql = func.get_aiomysql()

    return apps


if __name__ == '__main__':
    # wtf_tornado表单json初始
    init()

    # uvloop替换asyncio循环
    asyncio.set_event_loop_policy(EventLoopPolicy())
    # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    # 获取当前事件循环
    loop = asyncio.get_event_loop()

    # 封装tornado及一系列异步操作库
    app = make_app(loop)
    app.listen(8886, '0.0.0.0')

    # 事件循环启动, 永不停止
    loop.run_forever()
